import jwt
from datetime import datetime, timedelta

# 生成 JWT 令牌
def generate_token(user_id):
    # 设置有效时间
    expiration_time = datetime.utcnow() + timedelta(hours=24)  # 设置为 24 小时

    # 构建 payload
    payload = {
        'user_id': user_id,
        'exp': expiration_time
    }

    # 生成令牌
    token = jwt.encode(payload, 'bit104-503', algorithm='HS256')

    return token

# 验证 JWT 令牌
def verify_token(request):
    try:
        authorization_header = request.headers.get('Authorization')
        if authorization_header and authorization_header.startswith('Bearer '):
            # 提取令牌
            token = authorization_header.split(' ')[1]
            payload = jwt.decode(token, 'bit104-503', algorithms=['HS256'])
            user_id = payload.get('user_id')
            return user_id
        else:
            return None
        # 解码令牌
    except jwt.ExpiredSignatureError:
        # 令牌过期
        return None
    except jwt.InvalidTokenError:
        # 令牌无效
        return None

